import { BrowserWindow, shell } from 'electron'
import icon from '../../../resources/icon.png?asset'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'

export class MainFrame {
	#frame!: BrowserWindow
	#width = 900
	#height = 670
	// 创建窗口
	create() {
		this.#frame = new BrowserWindow({
			width: this.#width,
			height: this.#height,
			show: false,
			frame: false, // 无边框窗口
			resizable: false,// 不能调整窗口大小
			autoHideMenuBar: true,
			...(process.platform === 'linux' ? { icon } : {}),
			webPreferences: {
				preload: join(__dirname, '../preload/index.js'),
				sandbox: false
			}
		})

		this.#frame.on('ready-to-show', () => {
			this.#frame.show()
		})

		this.#frame.webContents.setWindowOpenHandler((details) => {
			shell.openExternal(details.url)
			return { action: 'deny' }
		})

		if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
			this.#frame.loadURL(process.env['ELECTRON_RENDERER_URL'])
		} else {
			this.#frame.loadFile(join(__dirname, '../renderer/index.html'))
		}
	}
	// 监听事件
	on(evevt, listener) {
		this.#frame.on(evevt, listener)
	}
	// 设置私有属性
	setSizeOnPrivate(w: number, h: number) {
		this.#width = w
		this.#height = h
	}
	// 获取当前大小
	getSize() {
		return this.#frame.getSize()
	}
	//隐藏窗口
	hide() {
		this.#frame.hide();
	}
	//关闭窗口
	close() {
		this.#frame.close();
	}
	//调整窗口位置
	setBounds(data: Partial<Electron.Rectangle>) {
		// 获取当前宽高并赋值给传入的data
		data.width = this.#width
		data.height = this.#height
		this.#frame.setBounds(data);
	}
	//最小化窗口
	minimize() {
		this.#frame.minimize();
	}
	//判断是否最大化
	isFullScreen() {
		return this.#frame.isFullScreen();
	}
	//放大 & 缩小
	setFullScreen(bool: boolean) {
		this.#frame.setFullScreen(bool);
	}
	//设置窗口大小
	setSize(w: number, h: number) {
		this.#frame.setSize(w, h);
		this.#width = w
		this.#height = h
	}
	//窗口居中
	center() {
		this.#frame.center();
	}
	//窗口是否可以改变 
	setResizable(bool: boolean) {
		this.#frame.setResizable(bool);
	}
	//窗口最小值
	setMinimumSize(w: number, h: number) {
		this.#frame.setMinimumSize(w, h);
	}
}